import React from 'react';
import PropTypes from 'prop-types';
import {
  Dialog,
  Form,
  Input,
  Field,
  Message,
  Select,
  Button,
  Checkbox,
  Tag,
  Radio,
  Switch,
  Balloon,
} from '@teamix/ui';
import { YunxiaoIcon, ButtonIcon, Title } from '@alife/devops-ui';
import { ENUM, ORGANIZATION_ADMIN_ROLES } from 'utils/constants.js';
import exceed from 'utils/apimap';
import utils from 'utils';
import { navigate, navigateHref, navigateOpen } from '@/utils/router';
import AccessSelect from '../accessSelect';
import debounce from 'lodash.debounce';
import { checkProjectName, getOrgCrypto } from 'api/index.js';
import track, { enterModal } from 'utils/track';
import { getFeature } from 'utils/features';
import GroupSelect from 'components/groupSelect';
import AddonBeforeInputSpan from 'components/addonBeforeInput/span';
import CreateGroupModal from 'components/createGroupModal';
import { access } from 'components/accessContainer/util';
import GuaranteeModal from './guaranteeModal';
import { setCachedRepoId, hasCachedRepoId } from 'utils/repoIdCache';
import './index.scss';
import docs from 'utils/docs';
import intl from '../../locale';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

const { organization } = window.FORCE;

const { Option } = Select;

const prefix = 'create-project-dialog';
const createProjectModalName = 'Dialog-NewRepo';
// 启用加密的key
const encryptNewProject = 'EncryptNewProject';

const serviceType = {
  template: ['init_standard_service', 'customize_service'],
  // 设计稿地址： https://udemo.alibaba-inc.com/preview#/preview/1612127/latest/iframe
  // 如果超过8有个更多，当前只有4个不做。后期扩展需看下设计稿
  details: [
    {
      name: intl.get({
        id: 'code-assets.components.createProjectModal.DataReport',
        defaultMessage: '数据报表',
      }),
      desc: intl.get({
        id: 'code-assets.components.createProjectModal.ProvidesRDDataReports',
        defaultMessage: '提供研发数据报表，洞察研发效能',
      }),
      key: 'report',
      // 埋点的action
      action: 'open_data_report',
    },

    {
      name: intl.get({
        id: 'code-assets.components.createProjectModal.CodeDetection',
        defaultMessage: '代码检测',
      }),
      desc: intl.get({
        id: 'code-assets.components.createProjectModal.ProvidesQualityAndSecurityTesting',
        defaultMessage: '提供质量&安全检测，保障编码安全',
      }),
      key: 'code_detection',
      action: 'open_code_scan',
    },

    // {
    //   name: intl.get({
    //     id: 'code-assets.components.createProjectModal.SyntaxService',
    //     defaultMessage: '语法服务',
    //   }),
    //   desc: intl.get({
    //     id: 'code-assets.components.createProjectModal.IntelligentNavigationServiceThatProvides',
    //     defaultMessage: '提供源码语法索引的智能导航服务',
    //   }),
    //   key: 'lsif',
    //   action: 'open_lsif',
    // },

    {
      name: intl.get({
        id: 'code-assets.components.createProjectModal.IntelligentReview',
        defaultMessage: '智能评审',
      }),
      desc: intl.get({
        id: 'code-assets.components.createProjectModal.IntelligentSeriesReviewProcessTo',
        defaultMessage: '智能串联评审流程，提升评审体验',
      }),
      key: 'smart_review',
      action: 'open_ai_codereview',
    },
  ],
};

const is_created_repo_with_service_key = 'is_created_repo_with_service';

export default class ProjectModal extends React.Component {
  static propTypes = {
    defaultNamespaceId: PropTypes.string,
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
    isModalOpen: PropTypes.bool,
    isSubgroup: PropTypes.bool,
    tbProjectName: PropTypes.string,
    okFn: PropTypes.func,
    onCreateSuccess: PropTypes.func,
  };

  static defaultProps = {
    defaultNamespaceId: '',
    trigger: null,
    closeModal: () => { },
    tbProjectName: '',
    okFn: () => { }, // 新建完成的回调
    onCreateSuccess: () => { }, // codeup新建库成功回调
    isSubgroup: false,
  };

  constructor(props) {
    super(props);
    this.field = new Field(this, {
      onChange: (name, value) => {
        if (name === 'namespace_id') {
          this.field.validate();
        }

        if (name === 'name') {
          this.field.setValue('path', value);
          this.field.validate();
        }
      },
    });

    this.state = {
      groupAccess: props.groupAccess || '',
      submitting: false,
      isModalOpen: false,
      // 组的校验是否需要必选校验
      groupSelectRules: [],
      // 聚焦时调整z-index
      namespaceIdFocus: false,
      createModalShow: false,
      group_creator_role: [],
      // 建库时，是否可以选择组
      is_group_enable: false,
      // 默认为空
      service_template: '',
      service_details: [],
      isServiceModalOpen: false,
      service_guarantee_checked: false,
      ignoreLangs: [],
      // 显示new
      hasServiceNewTag: !hasCachedRepoId(is_created_repo_with_service_key),
      groups: [],
      cryptoInfo: {},
      isCryptoInfoLoaded: false,
      createGroupModalData: {},
      searchValue: '',
      ignoreTypeRequired: false,
    };

    this.checkPath = debounce(this.checkPath, 500);
    this.checkName = debounce(this.checkName, 500);
    // 获取企业设置
    this.getGroupSettingData();
    this.getIgnoreTemplate();
    this.getOrgCryptoSettingData();
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  componentDidMount() {
    enterModal(createProjectModalName, {
      sendPV: false,
      sendPerf: false,
    });
  }

  getOrgCryptoSettingData = () => {
    getOrgCrypto().then((result) => {
      this.setState(
        {
          cryptoInfo: result,
          isCryptoInfoLoaded: true,
        },
        () => {
          this.field.setValue('is_crypto_enabled', result.crypto_level === encryptNewProject);
        },
      );
    });
  };

  getIgnoreTemplate = () => {
    exceed
      .fetch({
        api: 'project.file.ignore.lang',
      })
      .then((result) => {
        this.setState({
          ignoreLangs: result.git_ignore_types || [],
        });
      });
  };

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  setGroupAccess = (item) => {
    this.setState({
      groupAccess: item.visibility_level,
    });

    this.field.setValue({
      visibility_level: ENUM.visibility_level.PRIVATE,
    });
  };

  checkName(value, callback) {
    const { isSubgroup } = this.props;
    const { pathResource } = window.FORCE;

    let namespace_id = this.field.getValue('namespace_id');
    if (!Number(namespace_id)) {
      namespace_id = (isSubgroup ? pathResource.id : organization.namespace_id) || '';
    }
    checkProjectName({ name: value, namespace_id })
      .then(() => {
        callback();
      })
      .catch((err) => {
        const errCause = JSON.parse(err.responseText).cause;
        callback(`${errCause}`);
      });
  }

  checkPath(value, callback) {
    const { isSubgroup } = this.props;
    const { pathResource } = window.FORCE;

    let namespace_id = this.field.getValue('namespace_id');
    if (!Number(namespace_id)) {
      namespace_id = (isSubgroup ? pathResource.id : organization.namespace_id) || '';
    }

    checkProjectName({ path: value, namespace_id })
      .then(() => {
        callback();
      })
      .catch((err) => {
        const errCause = JSON.parse(err.responseText).cause;
        callback(`${errCause}`);
      });
  }

  nameValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (/^[a-zA-Z0-9_.][a-zA-Z0-9_.-]{0,}$/.test(value)) {
      this.checkName(value, callback);
    } else {
      callback(
        intl.get({
          id: 'code-assets.src.utils.locale.ItCanOnlyContainLetters',
          defaultMessage: "只能包含字母和数字、 '_'、 '.'和'-'，且只能以字母、数字或'_'开头",
        }),
      );
    }
  };

  pathValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (/^[a-zA-Z0-9_.][a-zA-Z0-9_.-]{0,}$/.test(value)) {
      const projectPath = this.getProjectPath();
      if (projectPath.length > 255) {
        callback(
          intl.get(
            {
              id: 'code-assets.components.createProjectModal.ThePathIsInvalidThe',
              defaultMessage:
                '路径不合法，路径总长度须小于 256 字符，当前共 {projectPathLength} 字符',
            },
            { projectPathLength: projectPath.length },
          ),
        );
        return;
      }
      this.checkPath(value, callback);
    } else {
      callback(
        intl.get({
          id: 'code-assets.src.utils.locale.ItCanOnlyContainLetters',
          defaultMessage: "只能包含字母和数字、 '_'、 '.'和'-'，且只能以字母、数字或'_'开头",
        }),
      );
    }
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.closeModal();
  };

  handleOk = () => {
    const { isSubgroup } = this.props;
    const { service_guarantee_checked } = this.state;
    this.setServiceError(service_guarantee_checked);
    this.field.validate((errors) => {
      if (!errors) {
        if (this.state.submitting) {
          return;
        }
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        // return;
        // 后台需要暂时先写上
        if (!Number(formData.namespace_id)) {
          // 判断是否在组内，进行数据设置
          const { pathResource } = window.FORCE;
          formData.namespace_id = (isSubgroup ? pathResource.id : organization.namespace_id) || '';
        }
        if (!formData.readme) {
          track({
            action: 'cancel_readme',
            page: createProjectModalName,
          });

          delete formData.readme_type;
        } else {
          // 集团不展示下拉框 保留checkbox为创建空模板
          track({
            action: 'set_readme',
            page: createProjectModalName,
          });

          if (formData.readme_type === 'user_guide') {
            track({
              action: 'set_readme_guidance',
              page: createProjectModalName,
            });
          } else if (formData.readme_type === 'empty') {
            track({
              action: 'set_readme_empty_template',
              page: createProjectModalName,
            });
          }
        }
        delete formData.readme;
        if (!formData.gitignore) {
          delete formData.gitignore_type;
        }
        delete formData.gitignore;
        if (formData.service_template === serviceType.template[0]) {
          formData[serviceType.template[0]] = true;
          delete formData.service_template;
          delete formData.service_details;
        } else {
          formData[serviceType.template[0]] = false;
          formData[serviceType.template[1]] = formData.service_details;
          delete formData.service_template;
          delete formData.service_details;
        }
        formData.open_department_id_paths = [];
        this.formSubmit(formData, (type) => {
          this.setState({ submitting: false });
          type !== 'isFail' && this.onClose();
        });
      }
    });
  };

  setVisibilityLevel = (value) => {
    this.field.setValue('visibility_level', value);
    // 全部禁用时需要提醒
    if (value === '' || value === undefined) {
      this.field.setError(
        'visibility_level',
        intl.get({
          id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
          defaultMessage: '该项为必填项',
        }),
      );
    } else {
      this.field.setError('visibility_level', '');
    }
  };

  getProjectPath = () => {
    const { isSubgroup } = this.props;
    const { groups } = this.state;
    const namespaceError = this.field.getError('namespace_id');
    const pathError = this.field.getError('path');
    const { pathResource } = window.FORCE;

    const path = this.field.getValue('path');
    const namespace_id = this.field.getValue('namespace_id');

    if (namespaceError || pathError || !path) {
      return null;
    }
    let projectPath = '';

    const origin = `${window.location.origin}`;
    let namespace = '';
    // selectedGroup直接根据数组过滤，防止setState数据延迟导致校验参数不准
    const selectedGroup = groups.find((item) => {
      return item.value === namespace_id;
    });
    if (isSubgroup) {
      namespace = `/${pathResource.fullPath}`;
    } else if (
      Number(namespace_id) !== Number(organization.namespace_id) &&
      selectedGroup &&
      selectedGroup.path_with_namespace
    ) {
      namespace = `/${selectedGroup.path_with_namespace}`;
    } else {
      namespace = `/${organization.path || organization.organization_id}`;
    }
    projectPath = `${origin}${namespace}/${path}`;

    return projectPath;
  };

  // 新增路径提示
  renderPath = () => {
    const projectPath = this.getProjectPath();
    let text = intl.get({
      id: 'code-assets.components.createProjectModal.CodeBasePathIs',
      defaultMessage: '代码库路径为：',
    });
    if (!projectPath) {
      text = 'Tips：建议使用代码组分组管理多个相关代码库';
    }
    return (
      <div className="project-path-tip">
        <div style={{ flex: 'none' }}>{text}</div>
        <Title trigger={<span>{projectPath}</span>} align="t">
          <span>{projectPath}</span>
        </Title>
      </div>
    );
  };

  formSubmit = (formData, cb) => {
    const { tbProjectName, tbProjectId } = this.props;
    exceed
      .fetch({
        api: tbProjectName ? 'tbProject.create.project' : 'projects.post',
        data: { ...formData, namespace_id: Number(formData.namespace_id) },
        params: tbProjectId ? { tbProjectId } : {},
      })
      .then((result) => {
        Message.success({
          title: intl.get({
            id: 'code-assets.components.createProjectModal.TheCodeLibraryIsCreated',
            defaultMessage: '代码库新建成功',
          }),
        });

        const href = `/${result.path_with_namespace}`;
        // 错误页面直接跳转
        const isErrorPage = window.ERROR && window.ERROR.errorCode;
        if (tbProjectName) {
          navigateOpen(href);
          this.props.okFn();
        } else if (isErrorPage) {
          navigateHref(href);
        } else {
          this.props.onCreateSuccess();
          navigate(href, { state: { forceUpdate: true } });
        }

        cb && cb();
        this.setState({
          hasServiceNewTag: false,
        });

        setCachedRepoId(is_created_repo_with_service_key);
      })
      .fail(() => {
        // 接口报错也要回调，以让按钮取消loading状态但是弹窗不关闭
        cb && cb('isFail');
      });
  };

  handleChangeAccess = (value) => {
    this.field.setValue('visibility_level', value);
  };

  setGroupNeedValidate = (isNeed) => {
    this.setState({
      groupSelectRules: isNeed
        ? [
          {
            required: true,
            message: intl.get({
              id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
              defaultMessage: '该项为必填项',
            }),
          },
        ]
        : [],
    });
  };

  getGroupSettingData = () => {
    exceed
      .forceFetch({
        api: 'organization.group.setting.get',
        params: {
          org_id: organization.id,
        },
      })
      .then((result) => {
        this.setState({
          group_creator_role: result.group_creator_role,
          is_group_enable: result.is_group_enable !== false,
        });
      });
  };

  getCreateGroupAccess = () => {
    const { group_creator_role } = this.state;
    const { user_role } = window.FORCE.organization;
    return (
      access(ORGANIZATION_ADMIN_ROLES, user_role) ||
      group_creator_role.map((item) => ENUM.access_level[item]).includes(user_role)
    );
  };

  toggleServiceType = (value) => {
    let service_details = [];
    let service_template = value;
    if (value === serviceType.template[0]) {
      service_details = serviceType.details.map((detail) => detail.key);
    }
    // 再次点击可以取消
    if (value === this.state.service_template) {
      service_template = '';
      service_details = [];
      // 重置校验
      this.setServiceError(true);
    }
    this.setState({
      service_template,
      service_details,
      service_guarantee_checked: false,
    });

    this.field.setValue('service_template', value);
    this.field.setValue('service_details', service_details);
    // 埋点
    track({
      action: value === serviceType.template[0] ? 'select_standard_template' : 'select_custom',
      page: 'Dialog-NewRepo',
      type: '',
      control: '',
    });
  };

  toggleServiceDetails = (value, action) => {
    const service_details = [...this.state.service_details];
    const index = service_details.indexOf(value);
    if (index > -1) {
      service_details.splice(index, 1);
    } else {
      service_details.push(value);
      track({
        action,
        page: 'Dialog-NewRepo',
        type: '',
        control: '',
      });
    }
    this.setState({
      service_details,
      service_guarantee_checked: false,
    });

    this.field.setValue('service_details', service_details);
  };

  setServiceError = (value) => {
    const { service_template, service_details } = this.state;
    if (service_template === 'customize_service' && service_details.length > 0) {
      this.field.setError(
        'service_detail',
        value
          ? ''
          : intl.get({
            id: 'code-assets.components.createProjectModal.ThisParameterIsRequired',
            defaultMessage: '该项为必填项',
          }),
      );
    } else if (service_template && service_template !== 'customize_service') {
      this.field.setError(
        'service_detail',
        value
          ? ''
          : intl.get({
            id: 'code-assets.components.createProjectModal.ThisParameterIsRequired',
            defaultMessage: '该项为必填项',
          }),
      );
    }
  };

  toggleServiceGuarantee = (value) => {
    const { service_details } = this.state;
    if (!service_details.length) {
      return;
    }
    this.setState({
      service_guarantee_checked: value,
    });

    this.setServiceError(value);
  };

  getCryptoEnableInfo = () => {
    const { cryptoInfo } = this.state;
    let isCryptoEnable = true;
    let cryptoDisabledTip = '';
    let cryptoBalloonType = 'primary';
    const isOrgAdmin = access(ORGANIZATION_ADMIN_ROLES, organization.user_role);
    // 未授权
    if (!cryptoInfo.service_authorization_id) {
      isCryptoEnable = false;
      cryptoBalloonType = isOrgAdmin ? 'normal' : 'primary';
      cryptoDisabledTip = isOrgAdmin ? (
        <div>
          {intl.get({
            id: 'code-assets.components.createProjectModal.TheServiceIsNotEnabled',
            defaultMessage: '暂未启用该服务，请前往企业安全中心-「',
          })}
          <a className="no-href-with-click " target="_blank" href="/settings/encryption">
            {intl.get({
              id: 'code-assets.components.createProjectModal.RepositoryEncryption',
              defaultMessage: '仓库加密',
            })}
          </a>
          {intl.get({
            id: 'code-assets.components.createProjectModal.Settings',
            defaultMessage: '」设置',
          })}
        </div>
      ) : (
        <div>
          {intl.get({
            id: 'code-assets.components.createProjectModal.YouAreNotAuthorizedTo',
            defaultMessage: '暂无权限使用该服务，请联系企业管理员处理',
          })}
        </div>
      );
    } else if (!isOrgAdmin && !cryptoInfo.project_settings_enabled) {
      isCryptoEnable = false;
      cryptoDisabledTip = (
        <div>
          {intl.get({
            id: 'code-assets.components.createProjectModal.YouAreNotAuthorizedTo',
            defaultMessage: '暂无权限使用该服务，请联系企业管理员处理',
          })}
        </div>
      );
    }

    return {
      isCryptoEnable,
      cryptoDisabledTip,
      cryptoBalloonType,
    };
  };

  handleSearch = (v) => {
    if (this.searchTimeout) {
      clearTimeout(this.searchTimeout);
    }
    this.searchTimeout = setTimeout(() => {
      this.setState({
        searchValue: v.toLocaleLowerCase(),
      });
    }, 100);
  };

  messageValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (value.length > 1000) {
      callback('描述长度不能超过1000');
    } else {
      callback();
    }
  };

  render() {
    const { init } = this.field;
    const { tbProjectName, isSubgroup } = this.props;
    const {
      groupSelectRules,
      namespaceIdFocus,
      hasServiceNewTag,
      createModalShow,
      service_template,
      service_details,
      isServiceModalOpen,
      service_guarantee_checked,
      is_group_enable,
      ignoreLangs,
      isCryptoInfoLoaded,
      searchValue,
    } = this.state;
    // 判断是否在组内，进行数据设置
    const { pathResource } = window.FORCE;
    const hasCreateGroupAccess = this.getCreateGroupAccess();
    // 一键开始服务或者自定义开启服务
    const is_service_template_all = serviceType.template[0] === service_template;
    const is_service_template_choose = serviceType.template[1] === service_template;

    const { isCryptoEnable, cryptoDisabledTip, cryptoBalloonType } = this.getCryptoEnableInfo();

    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            // align="tc tc"
            className={`${prefix}`}
            title={intl.get({
              id: 'code-assets.src.utils.locale.CreateACodeLibrary',
              defaultMessage: '新建代码库',
            })}
            visible
            style={{ width: '1000px' }}
            onClose={this.onClose}
            footer={
              <div className="create-project-footer">
                <div className="create-project-footer-left">
                  {tbProjectName && (
                    <span>
                      <YunxiaoIcon type="relevance-line" style={{ marginRight: 8 }} />
                      {intl.get({
                        id: 'code-assets.components.createProjectModal.Associated',
                        defaultMessage: '关联到',
                      })}
                      {tbProjectName}
                    </span>
                  )}
                </div>
                <div className="create-project-footer-right">
                  <Button type="normal" onClick={this.onClose}>
                    {intl.get({
                      id: 'code-assets.components.createProjectModal.Cancel',
                      defaultMessage: '取消',
                    })}
                  </Button>
                  <Button
                    type="primary"
                    onClick={this.handleOk}
                    loading={!!this.state.submitting}
                    style={{ marginLeft: 12 }}
                  >
                    {intl.get({
                      id: 'code-assets.components.createProjectModal.Determine',
                      defaultMessage: '确定',
                    })}
                  </Button>
                </div>
              </div>
            }
          >
            <div className={`${prefix}-content`}>
              <div className={`${prefix}-img-container`}>
                <img
                  style={{ width: '100%' }}
                  alt=""
                  src="https://img.alicdn.com/imgextra/i3/O1CN01g7t0r51Od0hDerDYA_!!6000000001727-2-tps-640-1000.png"
                />
              </div>
              <div className={`${prefix}-form`}>
                <Form {...formItemLayout} field={this.field} labelAlign="top">
                  <FormItem
                    label={
                      <span className={`${prefix}-label`}>
                        {intl.get({
                          id: 'code-assets.src.utils.locale.CodeLibraryName',
                          defaultMessage: '代码库名称',
                        })}
                      </span>
                    }
                    required
                  >
                    <Input
                      autoFocus
                      maxLength={100}
                      hasLimitHint
                      spellCheck={false}
                      placeholder={intl.get({
                        id: 'code-assets.src.utils.locale.EnterACodeLibraryName',
                        defaultMessage: '请输入代码库名称',
                      })}
                      {...init('name', {
                        rules: [
                          {
                            required: true,
                            message: intl.get({
                              id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
                              defaultMessage: '该项为必填项',
                            }),
                          },

                          {
                            validator: this.nameValidator,
                          },
                        ],
                      })}
                    />
                  </FormItem>

                  <div className="create-project-modal-path">
                    <FormItem
                      label={
                        <span className={`${prefix}-label`} style={{ float: 'left' }}>
                          {intl.get({
                            id: 'code-assets.components.createProjectModal.CodeLibraryPath',
                            defaultMessage: '代码库路径',
                          })}
                        </span>
                      }
                      required
                      className="origin"
                    >
                      <AddonBeforeInputSpan
                        text={`${window.location.origin}/${organization.path || organization.organization_id
                          }`}
                        show={`${window.location.origin}/${'.../'}`}
                      />
                    </FormItem>
                    {/* 子代码组为禁用 */}
                    {isSubgroup ? (
                      <FormItem label=" " className={'namespace_id'}>
                        <Select style={{ width: '100%' }} disabled value={pathResource.id}>
                          <Select.Option value={pathResource.id}>
                            {utils.getGroupPath(pathResource.fullPath)}
                          </Select.Option>
                        </Select>
                      </FormItem>
                    ) : (
                      <React.Fragment>
                        {is_group_enable ? (
                          <FormItem
                            label=" "
                            className={`namespace_id ${namespaceIdFocus ? 'focus' : ''}`}
                          >
                            <GroupSelect
                              {...init('namespace_id', {
                                rules: groupSelectRules,
                              })}
                              projectModalSetValue={this.state.createGroupModalData}
                              isDevops={!!tbProjectName}
                              hasGoGroup
                              goGroupModalFn={() => {
                                this.setState({
                                  createModalShow: true,
                                });
                              }}
                              hasCreateGroupAccess={hasCreateGroupAccess}
                              okFn={this.setGroupAccess}
                              style={{ width: '100%' }}
                              operateType={'create'}
                              type={'repo'}
                              setGroupNeedValidate={this.setGroupNeedValidate}
                              isUsePath
                              popupStyle={{ width: 320 }}
                              autoWidth={false}
                              onFocus={() => {
                                this.setState({
                                  namespaceIdFocus: true,
                                });
                              }}
                              onBlur={() => {
                                this.setState({
                                  namespaceIdFocus: false,
                                });
                              }}
                              initFn={(groups) => {
                                this.setState({
                                  groups,
                                });
                              }}
                            />
                          </FormItem>
                        ) : null}
                      </React.Fragment>
                    )}

                    <FormItem label=" " className={`path ${is_group_enable ? '' : 'no-group'}`}>
                      <Input
                        spellCheck={false}
                        placeholder={intl.get({
                          id: 'code-assets.components.createProjectModal.EnterTheCodeLibraryPath',
                          defaultMessage: '请输入代码库路径',
                        })}
                        {...init('path', {
                          rules: [
                            {
                              required: true,
                              message: intl.get({
                                id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
                                defaultMessage: '该项为必填项',
                              }),
                            },

                            {
                              validator: this.pathValidator,
                            },
                          ],
                        })}
                      />
                    </FormItem>
                  </div>
                  {/* 增加路径提示 */}
                  {!this.field.getError('path') && this.renderPath()}
                  <FormItem
                    required
                    className={`${prefix}-form-item`}
                    label={
                      <span>
                        <span className="before-icon-text">
                          <span className={`${prefix}-label`}>
                            {intl.get({
                              id: 'code-assets.src.utils.locale.Openness',
                              defaultMessage: '公开性',
                            })}
                          </span>
                        </span>
                      </span>
                    }
                  >
                    <AccessSelect
                      placeholder={intl.get({
                        id: 'code-assets.src.utils.locale.SelectPublicity',
                        defaultMessage: '请选择公开性',
                      })}
                      {...init('visibility_level', {
                        initValue: ENUM.visibility_level.PRIVATE,
                        rules: [
                          {
                            required: true,
                            message: intl.get({
                              id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
                              defaultMessage: '该项为必填项',
                            }),
                          },
                        ],
                      })}
                      groupAccess={this.state.groupAccess}
                      onChange={this.handleChangeAccess}
                      initValueFn={this.setVisibilityLevel}
                      style={{ width: 324 }}
                    />
                  </FormItem>
                  <FormItem
                    className={`${prefix}-form-item`}
                    label={
                      <span className={`${prefix}-label`}>
                        {intl.get({
                          id: 'code-assets.src.utils.locale.Description.1',
                          defaultMessage: '代码库描述',
                        })}
                      </span>
                    }
                    validator={this.checkPass2}
                  >
                    <Input.TextArea
                      placeholder={intl.get({
                        id: 'code-assets.src.utils.locale.EnterADescription',
                        defaultMessage: '请输入描述',
                      })}
                      {...init('description', { rules: [{ validator: this.messageValidator }] })}
                      rows={3}
                    />
                  </FormItem>
                  <FormItem
                    className={`${prefix}-form-item ${this.field.getState('service_detail') === 'error' ? 'has-error' : ''
                      }`}
                    label={
                      <span className={`${prefix}-label`}>
                        {intl.get({
                          id: 'code-assets.components.createProjectModal.QuickInitialization',
                          defaultMessage: '快速初始化',
                        })}

                        {hasServiceNewTag && (
                          <span style={{ position: 'relative', top: -1, left: 4 }}>
                            <Tag type="primary" style={{ margin: 0 }}>
                              New
                            </Tag>
                          </span>
                        )}
                      </span>
                    }
                    style={{ marginBottom: 20 }}
                    validator={this.checkPass2}
                    help={
                      this.field.getState('service_detail') === 'error' ? (
                        <div>
                          <YunxiaoIcon type="delete-fill" />
                          <span className="next-form-item-help-text">
                            {this.field.getError('service_detail')}
                          </span>
                        </div>
                      ) : (
                        ''
                      )
                    }
                  >
                    <div className={`${prefix}-service-type`}>
                      <div
                        className={`${prefix}-service-type-item ${is_service_template_all ? 'selected' : ''
                          }`}
                        onClick={() => {
                          this.toggleServiceType(serviceType.template[0]);
                        }}
                      >
                        <div className="icon-radio">
                          <div className="all">
                            <YunxiaoIcon type="task-line" style={{ color: '#868fff' }} />
                          </div>
                          <div>
                            {' '}
                            <Radio checked={is_service_template_all} />
                          </div>
                        </div>
                        <div className="item-title">
                          {intl.get({
                            id: 'code-assets.components.createProjectModal.StandardIntelligentWarehouse',
                            defaultMessage: '标准智能化仓库',
                          })}

                          <a
                            href={docs('create_repo_with_service')}
                            target="_blank"
                            className="item-title-icon"
                            rel="noreferrer"
                          >
                            {intl.get({
                              id: 'code-assets.components.createProjectModal.LearnMore',
                              defaultMessage: '了解更多',
                            })}
                          </a>
                        </div>
                        <div className="item-desc">
                          {intl.get({
                            id: 'code-assets.components.createProjectModal.EnableAlibabaIntelligentAlgorithmService',
                            defaultMessage: '一键启用阿里巴巴智能算法服务',
                          })}
                          <br />
                          报表分析 | 代码检测 | 智能评审等
                        </div>
                      </div>
                      <div
                        className={`${prefix}-service-type-item ${is_service_template_choose ? 'selected' : ''
                          }`}
                        onClick={() => {
                          this.field.setError('service_detail', '');
                          this.toggleServiceType(serviceType.template[1]);
                        }}
                      >
                        <div className="icon-radio">
                          <div className="choose">
                            <YunxiaoIcon type="setting-line" style={{ color: '#1b9aee' }} />
                          </div>
                          <div>
                            {' '}
                            <Radio checked={is_service_template_choose} />
                          </div>
                        </div>
                        <div className="item-title">
                          {intl.get({
                            id: 'code-assets.components.createProjectModal.Custom',
                            defaultMessage: '自定义',
                          })}

                          <a
                            href={docs('create_repo_with_service')}
                            target="_blank"
                            className="item-title-icon"
                            onClick={() => {
                              track({
                                action: 'to_learn_more',
                                page: 'Dialog-NewRepo',
                                type: '',
                                control: '',
                              });
                            }}
                            rel="noreferrer"
                          >
                            {intl.get({
                              id: 'code-assets.components.createProjectModal.LearnMore',
                              defaultMessage: '了解更多',
                            })}
                          </a>
                        </div>
                        <div className="item-desc">
                          {intl.get({
                            id: 'code-assets.components.createProjectModal.SelectTheSmartServiceThat',
                            defaultMessage: '请选择你期望启用的智能服务',
                          })}
                        </div>
                      </div>
                    </div>
                    {is_service_template_choose && (
                      <div className={`${prefix}-service-detail`}>
                        {serviceType.details.map((detail) => {
                          if (getFeature('project.create.initial.custom.not_need').includes(detail.key)) {
                            return null;
                          }
                          return (
                            <div className={`${prefix}-service-detail-item`} key={detail.key}>
                              <div className="detail-content">
                                <div>
                                  <div className="detail-title">{detail.name}</div>
                                  <div className="detail-desc">{detail.desc}</div>
                                </div>
                                <Switch
                                  checked={service_details.includes(detail.key)}
                                  onChange={() => {
                                    this.toggleServiceDetails(detail.key, detail.action);
                                  }}
                                />
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    )}

                    {(is_service_template_choose || is_service_template_all) && (
                      <div
                        className={`${prefix}-service-confirm ${is_service_template_choose ? 'no-border-top-radius' : ''
                          }`}
                      >
                        <Checkbox
                          checked={service_guarantee_checked}
                          onChange={this.toggleServiceGuarantee}
                          disabled={!service_details.length}
                          className="service-confirm-checkbox"
                        >
                          {intl.get({
                            id: 'code-assets.components.createProjectModal.IHaveReadAndAgreed',
                            defaultMessage: '我已阅读并同意',
                          })}
                        </Checkbox>
                        <a
                          className={`no-href-with-click ${service_details.length ? '' : 'disabled'
                            }`}
                          onClick={(e) => {
                            e.stopPropagation();
                            if (service_details.length) {
                              this.setState({
                                isServiceModalOpen: true,
                              });
                            }
                          }}
                        >
                          {intl.get({
                            id: 'code-assets.components.createProjectModal.ServiceActivationAgreement',
                            defaultMessage: '服务开通协议',
                          })}
                        </a>
                      </div>
                    )}
                  </FormItem>

                  {getFeature('module_enable.org.repository_encryption') && isCryptoInfoLoaded && (
                    <FormItem
                      className={`${prefix}-form-item`}
                      {...init('is_crypto_enabled', {
                        initValue: false,
                      })}
                      size="large"
                      style={{ marginBottom: 20 }}
                    >
                      {isCryptoEnable ? (
                        <Checkbox
                          label={
                            <span className={`${prefix}-label`}>
                              {intl.get({
                                id: 'code-assets.components.createProjectModal.EnableRepositoryEncryption',
                                defaultMessage: '启用仓库加密',
                              })}
                            </span>
                          }
                          size="large"
                          checked={this.field.getValue('is_crypto_enabled')}
                        />
                      ) : (
                        <Balloon
                          popupStyle={{
                            maxWidth: 'unset',
                          }}
                          closable={false}
                          followTrigger
                          align="t"
                          type={cryptoBalloonType}
                          trigger={
                            <Checkbox
                              disabled
                              label={
                                <span className={`${prefix}-label`}>
                                  {intl.get({
                                    id: 'code-assets.components.createProjectModal.EnableRepositoryEncryption',
                                    defaultMessage: '启用仓库加密',
                                  })}
                                </span>
                              }
                              size="large"
                            />
                          }
                        >
                          {cryptoDisabledTip}
                        </Balloon>
                      )}

                      <Balloon
                        closable={false}
                        followTrigger
                        trigger={<ButtonIcon type="secondary" name="question-line" />}
                        align="t"
                      >
                        <a href={docs('crypto')} target="_blank" rel="noreferrer">
                          {intl.get({
                            id: 'code-assets.components.createProjectModal.WhatIsWarehouseEncryption',
                            defaultMessage: '什么是仓库加密？',
                          })}
                        </a>
                      </Balloon>
                    </FormItem>
                  )}

                  <FormItem className={`${prefix}-form-item`} style={{ marginBottom: 20 }}>
                    <div>
                      <Checkbox
                        label={
                          <span className={`${prefix}-label`}>
                            {intl.get({
                              id: 'code-assets.components.createProjectModal.CreateReadmeMd',
                              defaultMessage: '创建 README.md',
                            })}
                          </span>
                        }
                        defaultValue={false}
                        {...init('readme')}
                      />

                      <Select
                        style={{
                          marginLeft: '4px',
                          verticalAlign: 'middle',
                        }}
                        {...init('readme_type', {
                          initValue: 'user_guide',
                        })}
                      >
                        <Option value="user_guide">
                          <span className={`${prefix}-label`}>
                            {intl.get({
                              id: 'code-assets.src.utils.locale.BuiltInBeginnerGuide',
                              defaultMessage: '内置新手引导',
                            })}
                          </span>
                        </Option>
                        <Option value="empty">
                          <span className={`${prefix}-label`}>
                            {intl.get({
                              id: 'code-assets.src.utils.locale.CreateAnEmptyTemplate',
                              defaultMessage: '创建空模板',
                            })}
                          </span>
                        </Option>
                      </Select>
                    </div>
                  </FormItem>
                  {getFeature('project.create.ignore') && (
                    <div style={{ display: 'flex' }}>
                      <FormItem className={`${prefix}-form-item`}>
                        <Checkbox
                          label={
                            <span className={`${prefix}-label`}>
                              {intl.get({
                                id: 'code-assets.components.createProjectModal.CreateGitignore',
                                defaultMessage: '创建 .gitignore',
                              })}
                            </span>
                          }
                          defaultValue={false}
                          {...init('gitignore', {
                            props: {
                              onChange: (value) => {
                                this.setState({
                                  ignoreTypeRequired: value,
                                });

                                if (value) {
                                  track({
                                    action: 'create_gitignore',
                                    page: 'Dialog-NewRepo',
                                    type: '',
                                    control: '',
                                  });
                                }
                              },
                            },
                          })}
                        />
                      </FormItem>
                      <FormItem className={`${prefix}-form-item-gitignore-form-item`}>
                        <Select
                          style={{
                            marginLeft: '4px',
                            verticalAlign: 'middle',
                          }}
                          {...init('gitignore_type', {
                            initValue: '',
                            rules: [
                              {
                                required: this.state.ignoreTypeRequired,
                                message: intl.get({
                                  id: 'code-assets.components.createProjectModal.SelectATemplate',
                                  defaultMessage: '请选择模板',
                                }),
                              },
                            ],
                          })}
                          filterLocal={false}
                          onSearch={this.handleSearch}
                          showSearch
                          placeholder="请选择模板"
                        >
                          {ignoreLangs
                            .filter((v) => {
                              if (searchValue) {
                                return v.toLocaleLowerCase().indexOf(searchValue) !== -1;
                              }
                              return true;
                            })
                            .map((item) => {
                              return (
                                <Option value={item}>
                                  <span className={`${prefix}-label`}>{item}</span>
                                </Option>
                              );
                            })}
                        </Select>
                      </FormItem>
                    </div>
                  )}
                </Form>
              </div>
            </div>
            <div style={{ clear: 'both' }} />
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, {
            onClick: (e) => {
              this.props.trigger.props.onClick && this.props.trigger.props.onClick(e);
              this.showModal();
            },
          })}

        {hasCreateGroupAccess && createModalShow && (
          <CreateGroupModal
            isFromProjectModal
            closeModal={(result) => {
              this.setState({
                createModalShow: false,
                createGroupModalData: result,
              });
            }}
            isModalOpen={createModalShow}
          />
        )}

        {isServiceModalOpen && (
          <GuaranteeModal
            isModalOpen={isServiceModalOpen}
            taskNames={service_details.map((detail) => {
              let taskName = '';
              serviceType.details.forEach((detail2) => {
                if (detail2.key === detail) {
                  taskName = detail2.name;
                }
              });
              return taskName;
            })}
            closeFn={() => {
              this.setState({
                isServiceModalOpen: false,
              });
            }}
          />
        )}
      </React.Fragment>
    );
  }
}
